package com.feather.common.text;

import java.util.ArrayList;

/**
 * @author flogyin
 */
public class BytePool {
	private int					length;
	private ArrayList<byte[]>	pool	= new ArrayList<byte[]>();

	public int getLength() {
		return this.length;
	}

	public void addReaded(byte[] bytes) {
		if (bytes == null) {
			return;
		}
		pool.add(bytes);
		length += bytes.length;
	}

	public void addReaded(byte[] bytes, int offset) {
		if (bytes == null) {
			return;
		}
		if (offset > bytes.length) {
			offset = bytes.length;
		}
		if (offset <= 0) {
			return;
		}
		if (offset == bytes.length) {
			pool.add(bytes);
			length += bytes.length;
		} else {
			byte[] swap = new byte[offset];
			System.arraycopy(bytes, 0, swap, 0, offset);
			pool.add(swap);
			length += offset;
		}
	}

	public byte[] totalBytes() {
		if (length == 0) {
			return null;
		}
		int size = pool.size();
		byte[] res = new byte[length];
		int start = 0;
		for (int i = 0; i < size; i++) {
			byte[] temp = (byte[]) pool.get(i);
			System.arraycopy(temp, 0, res, start, temp.length);
			start += temp.length;
		}
		return res;
	}
}
